/*
 * @Author: HuRrongChao 1556810922@qq.com
 * @Date: 2024-04-17 20:06:55
 * @LastEditors: HuRrongChao
 * @LastEditTime: 2025-04-18 20:40:55
 */

// express模块
const express = require('express')
const jwt = require('jsonwebtoken')
const path = require('path')
const app = express()
const http = require('http')
const { Server } = require('socket.io')
const config = require('./jwt/config.js')
const { openPermissions, frontendUrl, socketOptions } = require('./config.js')

// 配置中间件
app.use(express.urlencoded({ extended: false }))

// 解决跨域
const cors = require('cors')
app.use(cors())

// 准备一个 token 验证的中间件
const pathArray = ['/login', '/getVideoList', '/video_list', '/refreshToken', '/avatar', '/thumb_list', '/getComment', '/getConfessionBarrages', '/getForumPosts']
app.use((req, res, next) => {
  let pathName = req.url.split('/')[1]
  const token = req.headers['authorization']
  const url = pathName.includes('?') ? '/' + pathName.split('?')[0] : '/' + pathName
  console.log(url)
  // 不需要验证的 请求地址
  if (pathArray.includes(url) || openPermissions) return next()
  // 来到这里表示需要 token 验证
  if (!token) return res.send({ message: '请携带 token 请求', code: 0 })

  jwt.verify(token, config.jwtSecretKey, (err, data) => {
    if (err && err.message === 'invalid token') return res.send
      ({
        message: '无效 token',
        code: 0,
        type: 'Ineffective_token'
      })
    else if (err && err.message === 'jwt expired') return res.send
      ({
        message: 'token 失效',
        code: 0,
        type: 'lapse_token'
      })
    else if (err) return res.send
      ({
        message: '未知错误',
        code: 0,
        type: 'unknown_error'
      })
    else next()
  })
})

// 引入body - parser模块，用来解析JSON数据以及URL编码数据
const bodyParser = require('body-parser');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

// 路由
const { router, initSocketServer } = require('./router.js')
const server = http.createServer(app)
const io = new Server(server, {
  cors: {
    origin: frontendUrl,  // 从 config 中获取前端URL
    ...socketOptions.cors // 从 config 中获取其他 socket 配置
  }
})

// 初始化 Socket.IO 服务器
initSocketServer(io)

app.use(router)
app.use('/file/upload', require('./upload/uploader'))


// 将保存好的图片暴露出去，使前端可以使用在线路径访问该图片
const UPLOAD_VIDEO = path.join(__dirname, './public/upload')
app.use(express.static(UPLOAD_VIDEO))

// 开启端口,允许所有访问
server.listen(require('./config').port, '0.0.0.0', () => {
  console.log('服务启动');
})